<template>
	<view class="almost-lottery">
		<!-- head -->
		<view class="almost-lottery__head">
		</view>
		<!-- lottery -->
		<view class="almost-lottery__wheel">
			<almost-lottery :lottery-size="lotteryConfig.lotterySize" :action-size="lotteryConfig.actionSize"
				:ring-count="2" :duration="1" :self-rotaty="false" :img-circled="true" :canvasCached="true"
				:prize-list="prizeList" :prize-index="prizeIndex" @reset-index="prizeIndex = -1"
				@draw-before="handleDrawBefore" @draw-start="handleDrawStart" @draw-end="handleDrawEnd"
				@finish="handleDrawFinish" v-if="prizeList.length" />
			<view class="almost-lottery__count">
				<text class="text">用户剩余 {{ userScore }} 积分</text>
			</view>
		</view>
		<!-- rule -->
		<view class="almost-lottery__rule">
			<view class="rule-head">
				<view class="line"></view>
				<text class="title">活动规则</text>
				<view class="line"></view>
			</view>
			<view class="rule-body">
				<view class="item">
					<view class="number">1</view>
					<view class="text">
						<text>抽奖细则：</text>
						<text>每次抽奖消耗{{ score }}积分。</text>
					</view>
				</view>
				<view class="item item-rule">
					<view class="number">2</view>
					<view class="text">
						<text>奖励说明：</text>
						<text>a.现金奖：系统会即时转入账户余额，可提现。</text>
						<text>b.实物奖：中奖后需联系客服领取</text>
						<text>c.贡献值奖：系统会即时转入贡献值账户，可在平台内使用。</text>
					</view>
				</view>
				<view class="item">
					<view class="number">3</view>
					<view class="text">本活动最终解释权归陕西汉江源公司所有</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import AlmostLottery from '@/uni_modules/almost-lottery/components/almost-lottery/almost-lottery.vue'
	export default {
		name: 'Home',
		components: {
			AlmostLottery
		},
		data() {
			return {
				// 开启调试模式
				isDev: true,

				// 以下是转盘配置相关数据
				lotteryConfig: {
					// 抽奖转盘的整体尺寸，单位rpx
					lotterySize: 600,
					// 抽奖按钮的尺寸，单位rpx
					actionSize: 200
				},

				// 以下是转盘 UI 配置
				// 转盘外环图，如有需要，请参考替换为自己的设计稿
				lotteryBg: require('@/static/img/lottery/lottery-bg.png'),
				// 抽奖按钮图
				actionBg: require('@/static/img/lottery/action-bg.png'),

				// 以下是奖品配置数据
				// 奖品数据
				prizeList: [],
				// 奖品是否设有库存
				onStock: true,
				// 中奖下标
				prizeIndex: -1,

				// 是否正在抽奖中，避免重复触发
				prizeing: false,

				// 以下为中奖概率有关数据
				// 是否由前端控制概率，默认不开启，强烈建议由后端控制
				onFrontend: false,
				// 权重随机数的最大值
				prizeWeightMax: 0,
				// 权重数组
				prizeWeightArr: [],
				//积分
				score: '',
				userScore:','
			}
		},
		computed: {

		},
		onShow() {
			this.getDrawInfo()
		},
		methods: {
			// 重新生成
			handleInitCanvas() {
				clearCacheFile()
				clearStore()

				this.prizeList = []
				this.getPrizeList()

			},
			//获取抽奖信息
			getDrawInfo() {
				let that = this
				that.$http.get('draw/info', {}).then((res) => {
					if (res.code == 200) {
						that.score = res.data.score
						that.userScore = res.data.userScore
					}
				})
			},
			// 获取奖品列表
			async getPrizeList() {
				let that = this
				uni.showLoading({
					title: '奖品准备中...'
				})

				// 等待接口返回的数据进一步处理
				let res = await that.requestApiGetPrizeList()
				console.log('获取奖品列表', res)

				if (res.ok) {
					let data = res.data
					if (data.length) {
						//改变键名
						let list = [];
						data.forEach(function(item) {
							let v = {};
							v['prizeId'] = item.id;
							v['prizeName'] = item.name;
							v['prizeImage'] = item.pic;
							list.push(v);
						})

						that.prizeList = list;
						//console.log(list);
						console.log('已获取到奖品列表数据，开始绘制抽奖转盘')
					}
				} else {
					uni.hideLoading()
					uni.showToast({
						title: '获取奖品失败',
						mask: true,
						icon: 'none'
					})
				}
			},
			// 模拟请求 获取奖品列表 接口，
			// 注意这里返回的是一个 Promise
			requestApiGetPrizeList() {
				let that = this
				//获取奖品
				return new Promise((resolve, reject) => {
					that.$http.get('draw/getPrizes', {}).then((res) => {
						if (res.code == 200) {
							resolve({
								ok: true,
								data: res.data
							})
						} else {
							uni.hideLoading()
							uni.showToast({
								title: res.msg,
								mask: true,
								icon: 'none'
							})
						}
					})
				})
			},
			// 抽奖开始之前
			handleDrawBefore(callback) {
				console.log('抽奖开始之前')
				let flag = true //控制是否往后执行

				// // 还有免费数次或者剩余金币足够抽一次
				// if (this.freeNum > 0 || this.goldCoin >= this.goldNum) {

				// 	// 更新免费次数或金币余额
				// 	if (this.freeNum > 0) {
				// 		this.freeNum--
				// 	} else if (this.goldCoin >= this.goldNum) {
				// 		this.goldCoin -= this.goldNum
				// 	}

				// 	flag = true
				// } else {
				// 	flag = false
				// 	uni.showToast({
				// 		title: '积分不足',
				// 		icon: 'error？',
				// 		duration: 1500,
				// 	})
				// }
				callback(flag)
			},
			// 本次抽奖开始
			handleDrawStart() {
				console.log('触发抽奖按钮')
				if (this.prizeing) return
				this.prizeing = true

				this.remoteGetPrizeIndex()
			},


			// 远程请求接口获取中奖下标
			remoteGetPrizeIndex() {
				let that = this;
				console.warn('###当前处于模拟的请求接口，并返回了中奖信息###')

				// 这里随机产生的 prizeId 是模拟后端返回的 prizeId
				that.$http.get('draw/drawing', {}).then((res) => {
					console.log(res)
					let prizeId = ''
					if (res.code == 200) {
						prizeId = res.data.id;
						let list = that.prizeList;
						// 拿到后端返回的 prizeId 后，开始循环比对得出那个中奖的数据
						for (let i = 0; i < list.length; i++) {
							let item = list[i]
							if (item.prizeId === prizeId) {
								// 中奖下标
								that.prizeIndex = i
								break
							}
						}
						//console.log('本次抽中奖品 =>', that.prizeList[that.prizeIndex].prizeName)
					}else{
						uni.showModal({
							content: res.msg,
							showCancel: false,
						})
					}
				})

			},
			// 本次抽奖结束
			handleDrawEnd() {
				console.log('旋转结束，执行拿到结果后到逻辑')
				this.userScore -= this.score

				// 旋转结束后，开始处理拿到结果后的逻辑
				let prizeName = this.prizeList[this.prizeIndex].prizeName
				let tipContent = ''

				if (prizeName === '谢谢参与') {
					tipContent = '很遗憾，没有中奖，请再接再厉！'
				} else {
					tipContent = `恭喜您，获得 ${prizeName} ！`
				}

				uni.showModal({
					content: tipContent,
					showCancel: false,
					complete: () => {
						this.prizeing = false
					}
				})
			},
			// 抽奖转盘绘制完成
			handleDrawFinish(res) {
				console.log('抽奖转盘绘制完成', res)

				if (res.ok) {
					// 计算结束绘制的时间
					if (console.timeEnd) {
						console.timeEnd('绘制转盘用时')
					}
				}

				let stoTimer = setTimeout(() => {
					stoTimer = null

					uni.hideLoading()
					uni.showToast({
						title: res.msg,
						mask: true,
						icon: 'none'
					})
				}, 50)
			}
		},
		onLoad() {
			this.prizeList = []
			this.getPrizeList()
		},
		onUnload() {
			uni.hideLoading()
		}
	}
</script>

<style lang="scss" scoped>
	.almost-lottery {
		flex: 1;
		// background-color: #ab0101;
		background-image: radial-gradient(#ab0101, #ff8653);
	}

	.almost-lottery__head {
		position: relative;
		width: 100%;
		height: 50px;
		background: url('~static/img/lottery/top-bg.png') no-repeat center center/cover;

		.action {
			position: relative;
			top: 400rpx;
			display: flex;
			justify-content: center;
			align-items: center;
			width: 480rpx;
			height: 88rpx;
			line-height: 88rpx;
			margin: 0 auto;
			color: #FFFFFF;
			font-size: 32rpx;
			background-color: rgba(255, 136, 61, 1);
			border-radius: 44rpx;
		}

		.action-shadow {
			box-shadow: 0px 14rpx 0px 0px rgba(235, 112, 36, 1);
		}

		.gold {
			width: 44rpx;
			height: 44rpx;
			margin-right: 10rpx;
			background-repeat: no-repeat;
			background-position: center center;
			background-size: contain;
			background-image: url("~static/img/lottery/gold.png");
		}

		.num {
			color: #F9FC31;
		}

		.tip {
			position: relative;
			top: 428rpx;
			color: #FFFFFF;
			font-size: 24rpx;
			text-align: center;
		}
	}

	.almost-lottery__wheel {
		text-align: center;

		.almost-lottery__count {
			display: flex;
			flex-direction: column;
			justify-content: center;
			align-items: center;
			text-align: center;
			padding: 40rpx 0;
		}

		.text {
			color: #FFFFFF;
			font-size: 24rpx;
		}
	}

	.almost-lottery__rule {
		padding: 0 28rpx;
		color: #FFF8CB;

		.rule-head {
			display: flex;
			justify-content: space-around;
			align-items: center;
			margin: 40rpx 0;

			.line {
				flex: 1;
				height: 1px;
				background-color: #FFF3A5;
			}

			.title {
				width: 280rpx;
				color: #F63857;
				line-height: 70rpx;
				text-align: center;
				margin: 0 20rpx;
				border-radius: 8rpx;
				background-image: linear-gradient(0deg, rgba(255, 242, 158, 1), rgba(255, 244, 168, 1));
			}
		}

		.rule-body {
			color: #FFF8CB;
			font-size: 24rpx;
			padding: 10rpx 0 40rpx;

			.item {
				display: flex;
				margin-bottom: 10rpx;
			}

			.number {
				position: relative;
				top: 4rpx;
				width: 28rpx;
				height: 28rpx;
				line-height: 28rpx;
				text-align: center;
				color: #F63857;
				background: #FFF8CB;
				border-radius: 50%;
				margin-right: 10rpx;
			}

			.text {
				flex: 1;
			}

			.item-rule .text {
				display: flex;
				flex-direction: column;
			}
		}
	}

	.almost-lottery__action-dev {
		display: flex;
		flex-direction: row;
		justify-content: center;
		align-items: center;
		width: 400rpx;
		height: 80rpx;
		border-radius: 10rpx;
		text-align: center;
		background-color: red;
		margin: 0 auto 40rpx;

		.text {
			color: #FFFFFF;
			font-size: 28rpx;
		}
	}

	.almost-lottery__popup-wrap {
		flex: 1;
		display: flex;
		justify-content: center;
		align-items: center;

		.almost-lottery {
			background: transparent;
		}
	}
</style>
